<script lang="ts" setup>
defineOptions({
  name: 'EditDrawer',
});
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { menuAdd, menuEdit } from '../data/api';
import { drawerFormSchema } from '../data/options';
import { useThrottleFn } from '@vueuse/core';
import { message } from 'ant-design-vue';

const emit = defineEmits(['success']);

const data: any = ref({});
const title = computed(() => {
  return data.value?.menuId ? '编辑菜单' : '新增菜单';
});

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/3',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => formApi.submitForm(),
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = drawerApi.getData();
      formApi.setValues({ ...data.value });
    }
  },
});

//  提交
const onSubmit = useThrottleFn(async (values: Record<string, any>) => {
  console.log(values);
  const { valid } = await formApi.validate();
  if (!valid) return;
  let query = values.menuId ? menuEdit : menuAdd;
  let res: any = await query({ ...values });
  console.log(res);
  drawerApi.close();
  message.success(res.message);
  emit('success');
}, 1000);

// 表单
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-0 pr-4 pt-4 pb-4',
  schema: drawerFormSchema,
  handleSubmit: onSubmit,
  // 所有表单项
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
});
</script>
<template>
  <Drawer :title="title">
    <BaseForm />
  </Drawer>
</template>
